<template>
		<view class="con">
			<view ref="fileInput" class="fileinput"></view>
			<image src="../static/chatFriend/swiper09.png" mode="aspectFill"></image>
		</view>
</template>

<script>

export default {
	props: {
		/**
		 * 模式  asyn异步；await同步
		 */
		reqMode: {
			value: String,
			default: "async"
		},
		reqUrl: {
			value: String,
			default: ""
		},
		filed:{
			value:String,
			default:"upload"
		}
	},
	mounted() {
		var input = document.createElement('input')  
		input.type = 'file'; 
		input.setAttribute("multiple","false")
		input.className = 'file';
		input.style.cssText = "opacity: 0;width: 45px;height:45px;position: relative;z-index: 30;"
		input.onchange = (event) => {  
			if( event.target.files.length > 0 ){
				this.files = event.target.files;
				if( this.reqMode == "async" ){
					this.uploadFile(null,null);
				}
			}
		}  
		this.$refs.fileInput.$el.appendChild(input)  
	},
	data() {
		return {
			files:[],
			resposeJson:""
		};
	},
	methods: {
		uploadFile:function(reqParams,callback){
			let that=this
			if( this.reqUrl == "" ){
				uni.showToast({
					title: "请求路径不能为空",
					duration: 2000
				 })
			}else{
				let fData = new FormData();
				//批量上传
				for(var j=0;j<this.files.length;j++){
					fData.append(this.filed+(j==0?'':j+1),this.files[j]);
				}
				if(null!= reqParams && Object.keys(reqParams).length>0){
					fData =this.convertObj( fData,reqParams )
				}
				console.log(fData)
				let xhr = new XMLHttpRequest();
				xhr.open("POST",this.reqUrl, true);
				let _this = this;
				xhr.onload = function(e) { 
					let resposeJson = JSON.parse(xhr.responseText);
					that.files.forEach(item => {
						console.log(item.name)
						console.log(item.size)
						that.$emit('sendFile',resposeJson.url,item.name,item.size)
					})
					
				};
				xhr.send(fData)
				xhr.timeout = 100000;
				xhr.ontimeout = function(event){
					uni.showToast({
						title: "上传超时",
						icon:'none',
						duration: 2000
					})
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.con{
	position: relative;
	width: 90rpx;
	height: 90rpx;
	overflow: hidden;
	image{
		width: 90rpx;
		height: 90rpx;
		position: absolute;
		top: 0;
		left: 0;
	}
	
}
</style>
